package weaver.interfaces.htsc.hrm;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.util.HashMap;
import java.util.Map;

public class OrganizationTimeSynDept {

    /***
     * @param url
     * @return
     */
    public Map<String,String> doDeptSyn(String url,String createTimeGreater,Map<String,String> headMap)
    {
        BaseBean bb = new BaseBean();
        bb.writeLog("OrganizationTimeSynDept--doDeptSyn");
        OrganizationSynUtil organizationSynUtil = new OrganizationSynUtil();

        int allcount = 0;
        int insertsuccesscount = 0;  //新增成功数量
        int inserterrorcount = 0;  //新增失败数量

        int updatesuccesscount = 0;  //更新成功数量
        int updateerrorcount = 0;  //更新错误数量

        int exceptioncount = 0; //异常数量

        Map<String,String> map = new HashMap<String,String>();
        JSONObject jsonObject = new JSONObject();
        bb.writeLog("createTimeGreater:"+createTimeGreater);
        jsonObject.put("createTimeGreater",createTimeGreater);
        String response = organizationSynUtil.sendPost(url,jsonObject.toJSONString(),headMap);
        //默认所有部门挂在华泰集团这个分部下
        String subcompanyid1 = organizationSynUtil.getSubcomIdByCode("HT0001");
        RecordSet rs = new RecordSet();
        JSONArray deptArray = JSONArray.parseArray(response);
        allcount = deptArray.size();
        for(int i=0;i<deptArray.size();i++)
        {
            JSONObject deptJson = deptArray.getJSONObject(i);
            String deptCode = deptJson.getString("deptCode");//部门编码
            String deptName = deptJson.getString("deptName");//部门名称
            String deptCodePath = deptJson.getString("deptCodePath");//部门编码
            String deptNamePath = deptJson.getString("deptNamePath");//部门名称路径
            String parentDeptCode = deptJson.getString("parentDeptCode");//上级部门编码
            String deptCity = Util.null2String(deptJson.getString("deptCity"));//部门所在城市
            String deptState = Util.null2String(deptJson.getString("deptState"));//部门状态
            //部门HRBP转换对应人员的ID
            String deptTypeName = Util.null2String(deptJson.getString("deptTypeName"));//部门类型1名称
            String deptTypeCode = Util.null2String(deptJson.getString("deptTypeCode"));//部门类型1编码
            String deptType2Name = Util.null2String(deptJson.getString("deptType2Name"));//部门类型2名称
            String deptType2Code = Util.null2String(deptJson.getString("deptType2Code"));//部门类型2编码
            String deptDepth = Util.null2String(deptJson.getString("deptDepth"));//部门树所在深度
            String deptSortNum = Util.null2String(deptJson.getString("deptSortNum"));//部门排序编码
            String isActive = Util.null2String(deptJson.getString("isActive")); //
            bb.writeLog("isActive:"+isActive);
            if(!"ACTIVE".equalsIgnoreCase(isActive)){
                deptState = "1";
            }
            String isLeafDept = "0";//是否没有子部门
            if(deptJson.getBoolean("isLeafDept"))
            {
                isLeafDept = "1";
            }
            String deptScaleLevelCode = Util.null2String(deptJson.getString("deptScaleLevelCode"));//部门规模代码
            String deptScaleLevelName = Util.null2String(deptJson.getString("deptScaleLevelName"));//部门规模名称
            String departmentType = deptJson.getString("departmentType");//自定义部门类型
            departmentType = organizationSynUtil.getDepartmentType(departmentType);
            //String docNumAbbreviation = Util.null2String(deptJson.getString("docNumAbbreviation"));//部门简称
            //String docNumber = Util.null2String(deptJson.getString("docNumber"));//部门简称
            String cmpAbbre = Util.null2String(deptJson.getString("cmpAbbre"),"null");//分公司简称

            //查询上级部门对应的ID
            String supDepid = null;
            if(!"".equals(parentDeptCode)){
                supDepid = organizationSynUtil.getDeptIdByCode(parentDeptCode)+"";
            }else {
                supDepid="0";
            }

            String increStatus = Util.null2String(deptJson.getString("increStatus"));
            if("CREATE".equalsIgnoreCase(increStatus) || "UPDATE".equalsIgnoreCase(increStatus))
            {
                try{
                    String deptId = organizationSynUtil.getDeptIdByCode(deptCode);
                    if(!"".equals(deptId)){ //更新部门数据
                        bb.writeLog(deptCode+":"+deptName+":"+"update"+":"+deptId);
                        String deptUpdateSql =  " update hrmdepartment set departmentmark='"+deptName+"',departmentname='"+deptName+"',canceled='"+deptState+"'," +
                                " subcompanyid1='"+subcompanyid1+"',showorder='"+deptSortNum+"', supdepid='"+supDepid+"'  where departmentcode='"+deptCode+"' ";
                        bb.writeLog(deptUpdateSql);
                        boolean flag = rs.executeUpdate(deptUpdateSql);
                        if(flag)
                        {
                            updatesuccesscount++;
                        }else{
                            updateerrorcount++;
                        }

                    }else{ //插入部门数据
                        bb.writeLog(deptCode+":"+deptName+":"+"insert");
                        String deptNum = Util.null2String(deptJson.getString("deptNum"));
                        int intdeptNum = 0;
                        try{
                            if(!"".equals(deptNum)){
                                intdeptNum = Util.getIntValue(deptNum);
                            }else{
                                intdeptNum = -1;
                            }
                        }catch (Exception e){
                            bb.writeLog("OrganizationSynTime-Exception-:"+e);
                            intdeptNum = -2;
                        }
                        if(intdeptNum >0)
                        {
                            String deptInsertSql = " insert into hrmdepartment(id,departmentmark,departmentname,departmentcode," +
                                    " canceled,subcompanyid1,supdepid,showorder) values(?,?,?,?,?,?,?,?) ";
                            boolean flag = rs.executeUpdate(deptInsertSql,new Object[]{intdeptNum,deptName,deptName,deptCode,deptState,subcompanyid1,supDepid,deptSortNum});
                            if(flag)
                            {
                                insertsuccesscount++;
                            }else{
                                inserterrorcount++;
                            }
                        }
                        deptId = organizationSynUtil.getDeptIdByCode(deptCode);
                    }


                    JSONArray departmentAreaManagers = deptJson.getJSONArray("departmentAreaManagers");//投行区域负责人
                    String txqyfzr = organizationSynUtil.getUserIdsByCodesObj(departmentAreaManagers); //主账号 多人
                    String parentSaleCode = Util.null2String(deptJson.getString("parentSaleCode"));
                    String deptDefinedId = organizationSynUtil.getDeptDefineidByDeptid(deptId);
                    bb.writeLog("deptDefinedId:"+deptDefinedId+"--deptName:"+deptName+"--deptCode:"+deptCode+"--parentSaleCode:"+parentSaleCode);

                    if(!"".equals(deptDefinedId)){
                        rs.writeLog(deptDefinedId+":"+" :update");
                        String deptUpdateSql2 = " update hrmdepartmentdefined set deptCodePath='"+deptCodePath+"',deptNamePath='"+deptNamePath+"',deptCity='"+deptCity+"',deptTypeName='"+deptTypeName+"',deptTypeCode='"+deptTypeCode+"',deptType2Name='"+deptType2Name+"',deptType2Code='"+deptType2Code+"'," +
                                                " deptDepth='"+deptDepth+"',isLeafDept='"+isLeafDept+"',deptScaleLevelCode='"+deptScaleLevelCode+"',deptScaleLevelName='"+deptScaleLevelName+"',departmentType='"+departmentType+"',cmpAbbre='"+cmpAbbre+"',txqyfzr='"+txqyfzr+"',parentSaleCode='"+parentSaleCode+"' where id="+deptDefinedId;
                        rs.writeLog(deptUpdateSql2);
                        rs.execute(deptUpdateSql2);
                    }else{
                        rs.writeLog(deptDefinedId+":"+":insert ");
                        String deptInsertSql2 = " insert into hrmdepartmentdefined(deptid,deptCodePath,deptNamePath,deptCity," +
                                " deptTypeName,deptTypeCode,deptType2Name,deptType2Code,deptDepth,isLeafDept," +
                                " deptScaleLevelCode,deptScaleLevelName,departmentType,cmpAbbre,txqyfzr,parentSaleCode) values(" +
                                ""+deptId+",'"+deptCodePath+"','"+deptNamePath+"','"+deptCity+"','"+deptTypeName+"'," +
                                "'"+deptTypeCode+"','"+deptType2Name+"','"+deptType2Code+"','"+deptDepth+"','"+isLeafDept+"','"+deptScaleLevelCode+"','"
                                + deptScaleLevelName+"','"+departmentType+"','"+cmpAbbre+"','"+txqyfzr+"','"+parentSaleCode+"') ";
                        rs.writeLog(deptInsertSql2);
                        rs.execute(deptInsertSql2);
                    }

//                    String deptabbrdefid = "" ;
//                    String sql = " select id from workflow_deptabbrdef where departmentid="+deptId;
//                    rs.execute(sql);
//                    if(rs.next()){
//                        deptabbrdefid = Util.null2String(rs.getString("id"));
//                    }
//                    if(!"".equals(deptabbrdefid)){
//                        sql = " update workflow_deptabbrdef set abbr='"+ docNumAbbreviation+"' where id="+deptabbrdefid ;
//                        rs.execute(sql);
//                    }else{
//                        sql = " insert into workflow_deptabbrdef(departmentid,abbr) values("+deptId+",'"+docNumAbbreviation+"') " ;
//                        rs.execute(sql);
//                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                    e.printStackTrace();
                    exceptioncount++;
                    rs.writeLog("部门编号为"+deptCode+"的数据同步失败，data:"+deptJson.toJSONString());
                }
            }else if("DELETE".equalsIgnoreCase(increStatus)){
                try{
                    String deptId = organizationSynUtil.getDeptIdByCode(deptCode);
                    if(!"".equals(deptId)){ //更新部门数据
                        bb.writeLog(deptCode+":"+deptName+":"+"DELETE");
                        String deptUpdateSql = " update hrmdepartment set canceled=1 where id=? ";
                        boolean flag = rs.executeUpdate(deptUpdateSql,new Object[]{deptId});

                        if(flag)
                        {
                            updatesuccesscount++;
                        }else{
                            updateerrorcount++;
                        }
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                    e.printStackTrace();
                    exceptioncount++;
                    rs.writeLog("部门编号为"+deptCode+"的数据同步失败，data:"+deptJson.toJSONString());
                }
            }
        }
        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("insertsuccesscount",insertsuccesscount+"");
        map.put("inserterrorcount",inserterrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        map.put("allcount",allcount+"");
        return map;
    }
}
